<?php
/**
 * Description: 直播课工具类
 * User: devforma
 * Date: 15/5/11
 * Time: 10:21
 */
require_once __DIR__ . '/utils.php';
require_once __DIR__ . '/MTCloud.class.php';

class LiveCourse {

    /**
     * 查询用户对某个公开课是否可见
     * @param Object $cmsdb 数据库操作集
     * @param int $userId 用户id
     * @param int $courseId 课程id
     * @param int $classId 课堂id
     * @param string $startTime 开始时间
     * @param int $limit 课程人数限制
     * @return bool
     */
    public static function isOpenCourseAvailable($cmsdb, $userId, $courseId, $classId, $startTime, $limit) {
        return true;
    }

    /**
     * 查询用户是否预约了公开课
     * @param Object $cmsdb 数据库操作集
     * @param int $userId 用户id
     * @param int $courseId 课程id
     * @return bool
     */
    public static function isOpenCourseBooked($cmsdb, $userId, $courseId) {
        $sql = 'SELECT `is_booked` FROM `gray_user_open_course` WHERE `user_id`=:user_id AND `course_id`=:course_id';
        $booked = $cmsdb->getVar($sql, array(':user_id' => $userId, ':course_id' => $courseId));

        return empty($booked) ? false : true;
    }


    /**
     * 获取静态课程页面url
     * @param int $uid 用户id
     * @param string $nickname 昵称
     * @param string $platform 客户端类型
     * @return string
     */
    public static function getStaticCourseUrl($uid, $nickname, $platform) {
        global $cmsdb;
        $url = getOption('staticCourseUrl');

        if (!empty($url) && strpos($url, 'http') !== false) { //网址
            return $url;
        } elseif (!empty($url) && is_numeric($url)) { //课程id

            $cacheKey = 'staticClass:' . $url;
            if (($staticClass = cacheGet($cacheKey)) == null) {
                $sql = 'SELECT cl.room_id, cl.id, cl.start_time FROM `data_live_class` AS cl INNER JOIN `relationship_live_class_and_course` AS r
                ON cl.id=r.class_id AND r.course_id='.$url;
                $staticClass = $cmsdb->getRow($sql);

                cacheAdd($cacheKey, $staticClass, 3600);
            }

            self::logEnter($uid, $url, $platform, explode(' ', $staticClass->start_time)[0], 1); //往期公开课进入记录

            return self::GetLiveClassUrl($uid, $nickname, $staticClass->room_id, true);
        } else {
            return '';
        }
    }

    /**
     * 记录往期公开课的进入情况
     * @param int $userId 用户id
     * @param int $courseId 课程id
     * @param string $platform 客户端类型
     * @param string $courseDate 课程时间
     * @param int $isStatic 是否为查看往期
     */
    public static function logEnter($userId, $courseId, $platform, $courseDate, $isStatic = 0) {
        global $uddb;
        $exists = $uddb->getVar('SELECT `id` FROM `openclass_enter_log` WHERE `course_id`=:cid AND `user_id`=:uid
        AND `is_static`=1', array(':cid' => $courseId, ':uid' => $userId));

        if (empty($exists))
            $uddb->insert('openclass_enter_log', array(
                'user_id' => $userId,
                'course_id' => $courseId,
                'platform' => $platform,
                'app' => empty($_GET['app_type']) ? '' : $_GET['app_type'],
                'enter_time' => date('Y-m-d H:i:s'),
                'course_date' => $courseDate,
                'is_static' => $isStatic,
                'promote_src' => empty($_GET['src']) ? '' : $_GET['src'],
            ));
    }

    /**
     * 获取公开课信息
     *
     * @param $courseId
     * @return mixed
     */
    public static function getOpenClassInfo($courseId) {
        global $cmsdb;

        //获取课堂信息
        $cacheKey = 'openclassroom:' . $courseId;
        $room = cacheGet($cacheKey);
        if (empty($room)) {
            $sql = 'SELECT c.id, c.room_id, c.live_platform, c.start_time, c.end_time, c.lector_id
            FROM `data_live_class` AS c, `relationship_live_class_and_course` AS r, `data_live_course` AS co
            WHERE c.id=r.class_id AND r.course_id=co.id AND co.id=:course_id AND co.type_id=1 AND co.publish_status="publish" LIMIT 1';
            $room = $cmsdb->getRow($sql, array(':course_id' => $courseId));
            if (empty($room))
                return false;

            //欢拓房间id
            $room->maituo_room_id = $cmsdb->getVar('SELECT `maituo_room_id` FROM `data_teacher` WHERE `id`=:tid',
                array(':tid' => $room->lector_id));

            cacheSet($cacheKey, $room, 3*60*60);
        }

        return $room;
    }

    /**
     * 获取已购课堂信息
     *
     * @param $courseId
     * @param $classId
     * @param $userId
     * @return bool|mixed
     */
    public static function getPurchasedClassInfo($courseId, $classId, $userId) {
        global $cmsdb;

        //是否购买过
        $purchased = $cmsdb->getVar('SELECT `id` FROM `relation_user_product` WHERE `user_id`=:uid AND `product_id`=:pid
            AND `product_type`="zhiboke" LIMIT 1', array(':uid' => $userId, ':pid' => $courseId));
        if (empty($purchased))
            return false;

        //课程和课堂是否对应
        $relation = $cmsdb->getVar('SELECT `id` FROM `relationship_live_class_and_course` WHERE `class_id`=:clid AND
            `course_id`=:coid LIMIT 1', array(':clid' => $classId, ':coid' => $courseId));
        if (empty($relation))
            return false;

        //获取课堂信息
        return getLiveClassInfo($classId);
    }


    /**
     * 获取课程详情
     * @param Object $cmsdb 数据库操作集
     * @param int $courseId 课程id
     */
    public static function getCourseDetail($cmsdb, $courseId) {
        return $cmsdb->getRow('SELECT * FROM `data_live_course` WHERE `id`=:course_id AND `type_id`=1',
            array(':course_id' => $courseId));
    }

    /**
     * 获取欢拓云播放地址
     *
     * @param $classId
     * @param $mtRoomId
     * @param $userId
     * @param $nickname
     * @param bool $isEnded
     * @param string $role
     * @return string
     */
    public static function GetHtClassUrl($classId, $mtRoomId, $userId, $nickname, $isEnded = false, $role = 'user') {
        global $cmsdb;
        $mt = new MTCloud();

        if (!$isEnded) { //未结束
            $result = $mt->userAccess($userId, $nickname, $role, $mtRoomId);

        } else { //回放
            $liveRecord = $cmsdb->getRow('SELECT `liveid`, `status` FROM `data_htlive_class` WHERE `class_id`=:cid',
                array(':cid' => $classId));

            if (empty($liveRecord) || $liveRecord->status !== 'playback') {
                return '';
            }

            $result = $mt->userAccessPlayback($userId, $nickname, $role, $liveRecord->liveid);
        }

        if (is_array($result) && $result['code'] == 0) {
            return $result['data']['shortUrl'];
        } else {
            return '';
        }
    }


    /**
     * 获取直播课播放地址
     * @param int $uid 用户id
     * @param string $nickname 昵称
     * @param string $roomId 房间id
     * @param bool $isH5 是否为H5
     * @return string
     */
    public static function GetLiveClassUrl($uid, $nickname, $roomId, $isH5 = false) {
        if ($isH5) {
            $api = "http://api.duobeiyun.com/api/v3/room/enter?";
        } else {
            $api = "http://api.jiangzuotong.com/api/v2/room/enter?";
        }

        $params = array(
            'nickname' => trim($nickname),
            'partner' => '20140807101355',
            'roomId' => $roomId,
            'timestamp' => time() * 1000,
            'uid' => $uid,
            'userRole' => 2 //2为学生上课地址
        );


        /*****************************************************
         * 生成签名
         */
        ksort($params);

        $paramStr = '';

        foreach($params as $param_key => $param_value) {
            $paramStr .= (strval($param_key).'='.strval($param_value).'&');
        }
        $sign = md5(rtrim($paramStr, '&').'771f3c17303c49f6a8dc3e3ffbf41990');


        /*****************************************************
         * 构造播放地址
         */
        $paramStr = '';

        foreach($params as $param_key => $param_value) {
            $paramStr .= (strval($param_key).'='.urlencode(strval($param_value)).'&');
        }

        $paramStr .= ('sign='.$sign);
        return $api.$paramStr;
    }

    /**
     * 获取课程参加人数
     *
     * @param $roomId
     * @return int
     */
    public static function getClassPersons($roomId) {
        $url = 'http://api.duobeiyun.com/api/v3/room/consumption/count';

        $params = array(
            'partner' => '20140807101355',
            'roomId' => $roomId,
            'timestamp' => time() * 1000
        );

        /*****************************************************
         * 生成签名
         */
        ksort($params);

        $paramStr = '';

        foreach ($params as $param_key => $param_value) {
            $paramStr .= (strval($param_key) . '=' . strval($param_value) . '&');
        }
        $sign = md5(rtrim($paramStr, '&') . '771f3c17303c49f6a8dc3e3ffbf41990');

        $params['sign'] = $sign;

        $data = httpPost($url, $params);

        if (!empty($data) && ($data = json_decode($data)) && $data->success)
            return $data->course->count;

        return 0;
    }

    /**
     * 获取当前最近的公开课(包含正在上课的)
     *
     * @return bool|object
     */
    public static function getLatestOpenCourse() {
        global $cmsdb;

        $datetime = date('Y-m-d H:i:s');

        $cacheKey = 'func:getLatestOpenCourse';

        //如果没有缓存,或缓存中的课程结束时间已过,则更新缓存
        if (($course = cacheGet($cacheKey)) == null || $course->class_endtime <= $datetime) {
            $sql = "SELECT `id`, `course_name`, `class_starttime`, `class_endtime` FROM `data_live_course` WHERE 
            `class_endtime`>'{$datetime}' AND `type_id`=1 AND `publish_status`='publish' ORDER BY `class_endtime`, `id` LIMIT 1";

            if ($course = $cmsdb->getRow($sql)) {
                cacheSet($cacheKey, $course, 3*60*60);
            } else {
                return false;
            }
        }

        return $course;
    }

    /**
     * 获取课程的由课堂计算得到的属性
     *
     * @param int $courseId 课程id
     * @return array
     */
    public static function getComputedCourseInfo($courseId) {
        global $cmsdb;

        $cacheKey = 'LiveCourse::getLiveCourseInfo:'.$courseId;
        if (($info = cacheGet($cacheKey)) == null) {

            //初始化计算变量
            $todayStart   = strtotime(date('Y-m-d'));
            $totalSeconds = 0;
            $now          = time();
            $teachers     = array();
            $todayClasses = array();
            $isOnair      = false;

            //获取该课程下所有课堂信息
            $sql = 'SELECT c.id, c.class_name, c.start_time, c.end_time, c.lector_id, c.room_id, c.courseware_link, 
            c.related_paper_id, c.live_platform platform, t.name AS lector_name, t.introduction, t.avatar, t.grade_score 
            FROM `data_live_class` AS c, `relationship_live_class_and_course` AS r, `data_teacher` AS t 
            WHERE r.course_id=:cid AND c.id=r.class_id AND t.id=c.lector_id';
            $classes = (array)$cmsdb->getResults($sql, array(':cid' => $courseId));

            //编辑课堂计算相关属性
            foreach ($classes as $classInfo) {
                if (!isset($teachers[$classInfo->lector_id]))
                    $teachers[$classInfo->lector_id] = $classInfo->lector_name;

                //课堂开始结束时间
                $classStart = strtotime($classInfo->start_time);
                $classEnd = strtotime($classInfo->end_time);

                //课程总时长
                $totalSeconds += $classEnd - $classStart;

                //今日课堂
                if ($classStart > $todayStart && $classStart < $todayStart + 24*3600) {
                    $todayClasses[] = array(
                        'id' => intval($classInfo->id),
                        'name' => $classInfo->class_name,
                        'start_time' => $classInfo->start_time,
                        'end_time' => $classInfo->end_time,
                        'lector' => $classInfo->lector_name
                    );
                }

                //课程有课堂正在直播
                if ($classStart <= $now && $classEnd >= $now) {
                    $isOnair = true;
                }
            }

            //缓存
            $info = array(
                'lectors'       => $teachers,
                'today_classes' => $todayClasses,
                'periods'       => $totalSeconds,
                'is_onair'      => $isOnair
            );
            cacheAdd($cacheKey, $info, 6*60*60);
        }

        return $info;
    }

}
